package org.csu.mypetstore.controller;

import org.csu.mypetstore.common.CommonResponse;
import org.csu.mypetstore.domain.LineItem;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.domain.User;
import org.csu.mypetstore.service.OrderService;
import org.csu.mypetstore.service.UserService;
import org.csu.mypetstore.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
//import javax.jws.WebParam;
//import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


@RestController
@Validated
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

//    @GetMapping("/viewSignin")
//    public String viewSignin(){
//        return "account/Signin";
//    }

//    @PostMapping("/search")
//    public String search(HttpServletRequest request,Model model){
//        String keyword;
//        keyword = request.getParameter("keyword");
//        User user;
//        user = userService.findUserByUsername(keyword);
//        if(user != null){
//             model.addAttribute("user",user);
//        return "/manage/changeUser" ;
//        }
//       else {
//           String message = "该用户不存在";
//            request.getSession().setAttribute("message",message);
//            List<User> userList=userService.getAllUser();
//
//                    model.addAttribute("message",message);
//         model.addAttribute("userList",userList);
//        return "/manage/userManage";
//        }
//    }
    @PostMapping("/search")
    public CommonResponse<Object> search(@RequestParam("keyword") String keyword){
        User user;
        user = userService.findUserByUsername(keyword);
        if(user != null){
            return CommonResponse.createForSuccess(user);
        }
        else {
            String message = "该用户不存在";
            List<User> userList=userService.getAllUser();
            return CommonResponse.createForSuccess(message,userList);

        }
    }
//    @GetMapping ("/remove")
//    public String remove(String username,Model model)
//    {
//        userService.remove(username);
//        List<User> userList = userService.getAllUser();
//        model.addAttribute("userList",userList);
//        return "/manage/userManage";
//    }
    @PostMapping ("/remove")
    public CommonResponse<Object> remove(@RequestParam("username") String username)
    {
        userService.remove(username);
        List<User> userList = userService.getAllUser();
        return CommonResponse.createForSuccess(userList);
    }

//    @GetMapping("/authCode")
//    public String authCode(HttpServletRequest request, HttpServletResponse response,Integer number) throws IOException {
//        AuthCodeUtil authCodeUtil=new AuthCodeUtil();
//        BufferedImage image = new BufferedImage(authCodeUtil.WIDTH,authCodeUtil.HEIGHT,BufferedImage.TYPE_INT_RGB);
//        Graphics g = image.getGraphics();
//        String authCode = "";
//        authCodeUtil.setBackground(g);
//        authCodeUtil.setBorder(g);
//        authCodeUtil.setRandomLine(g);
//        authCode = authCodeUtil.setWriteDate(g);
//
//
//        request.getSession().setAttribute("authCode",authCode);
//        response.setContentType("image/jpeg");
//        response.setHeader("Pragma","no-cache");
//        response.setHeader("Cache-control","no-cache");
//        response.setIntHeader("Expires",-1);
//        g.dispose();
//        ImageIO.write(image,"JPEG",response.getOutputStream());
//        return null;
//    }
    //图片验证码
    //todo:将值显示到前端
    @GetMapping("/authCode")
    public void authCode(HttpSession session, HttpServletResponse response,Integer number) throws IOException {
        AuthCodeUtil authCodeUtil=new AuthCodeUtil();
        BufferedImage image = new BufferedImage(authCodeUtil.WIDTH,authCodeUtil.HEIGHT,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        String authCode = "";
        authCodeUtil.setBackground(g);
        authCodeUtil.setBorder(g);
        authCodeUtil.setRandomLine(g);
        authCode = authCodeUtil.setWriteDate(g);
        System.out.println("*******************************************");
        System.out.println("当前验证码："+authCode);
        System.out.println("*******************************************");
        session.removeAttribute(authCode);
        session.setAttribute("authCode",authCode);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-control","no-cache");
        response.setIntHeader("Expires",-1);
        g.dispose();
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }

//    @PostMapping("/signin")
//    public String singin(HttpServletRequest request,String inputCode,User user,Model model){
//        String msg = null;
//        String authCode = (String)request.getSession().getAttribute("authCode");
//
//        User loginResult = userService.signin(user);
//        if(!authCode.equals(inputCode)){
//            msg = "验证码有误！";
//            model.addAttribute("msg",msg);
//            return "/account/Signin";
//        }else if(loginResult == null){
//            msg = "用户名或密码不正确或不是管理员账户";
//            model.addAttribute("msg",msg);
//            return "/account/Signin";
//        }
//        else{
//            HttpSession session = request.getSession();
//            session.setAttribute("user",loginResult);
//            model.addAttribute("user",loginResult);
//            return "/catalog/Main";
//        }
//    }

   @PostMapping("/login")
    public CommonResponse<Object> singin(@RequestParam("id") String id,
                                         @RequestParam("password") String password,
                                         HttpSession session){
        String msg = null;
        User loginResult = userService.signin(id,password);
        if(loginResult == null){
            msg = "用户名或密码不正确或不是管理员账户";
            return CommonResponse.createForError(msg);
        }
        else{
            System.out.println(111);
            session.setAttribute("user",loginResult);
            System.out.println(session.getId());
            return CommonResponse.createForSuccess(loginResult);
        }
    }
    @GetMapping("/get_loginUser_info")
    @ResponseBody
    public CommonResponse<User> getLoginUserInfo(HttpSession session){
        User loginUser = (User) session.getAttribute("user");
        System.out.println("loginUser"+loginUser);
        if(loginUser !=null){
            return CommonResponse.createForSuccess("获取登录用户信息成功",loginUser);
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

//    @GetMapping("/fastSignin")
//    public String fastSignin(HttpServletRequest request,HttpSession session,Model model){
//        User user = new User();
//        user.setUsername("1234");
//        user.setPassword("1234");
//
//        User loginResult = userService.signin(user);
//        System.out.println("当前使用1234登陆");
//        //HttpSession session = request.getSession();
//        session.setAttribute("user",loginResult);
//        model.addAttribute("user",loginResult);
//        return "/catalog/Main";
//    }
    @GetMapping("/fastSignin")
    public CommonResponse<Object> fastSignin(HttpSession session){
        User user = new User();
        user.setUsername("1234");
        user.setPassword("1234");

        User loginResult = userService.signin("1234","1234");
        System.out.println("当前使用1234登陆");
        //HttpSession session = request.getSession();
        session.setAttribute("user",loginResult);
        return CommonResponse.createForSuccess(loginResult);
    }
     @GetMapping("/getAuthCode")
    @ResponseBody

    public CommonResponse<User> getAuthCode(HttpSession session){
        String authCode = (String)session.getAttribute("authCode");
//        System.out.println(authCode);
        if (authCode==null)return CommonResponse.createForError("验证码未创建");
        else {
            session.removeAttribute("authCode");
            return CommonResponse.createForSuccessMessage(authCode);
        }
    }

//    @GetMapping("/signout")
//    public String signout(HttpServletRequest request){
//        if(request.getSession().getAttribute("user") != null) {
//            request.getSession().removeAttribute("user");
//        }
//        return "/catalog/Main";
//    }

    @GetMapping("/viewMyAccount")
    public CommonResponse<Object> viewMyAccount(HttpSession session){
        User user = (User) session.getAttribute("user");
        if(user == null) {
            String msg = "请先登录后再查看MyAccount";
            return CommonResponse.createForError(msg);
        }
        return CommonResponse.createForSuccess(user);
    }
//    @GetMapping("/viewMyAccount")
//    public CommonResponse<Object> viewMyAccount(@RequestParam("user") User user){
//        if(user == null) {
//            String msg = "请先登录后再查看MyAccount";
//            return CommonResponse.createForError(msg);
//        }
//        User user=(User)request.getSession().getAttribute("user");
//        model.addAttribute("user",user);
//        return "/account/MyAccount";
//    }

//    @GetMapping("/viewRegister")
//    public String viewRegister(){
//        return "/account/Register";
//    }

//    @PostMapping("/register")
//    public String register(String password,String repeatpwd,HttpServletRequest request,User user,String inputCode,String inputVCode,Model model){
//        String reminder= null;
//        boolean result = false;
//        System.out.println(inputVCode);
//
//        if(!password.equals(repeatpwd)){
//            reminder = "两次输入密码不一致";
//            model.addAttribute("reminder",reminder);
//            return "/account/MyAccount";
//        }
//
//        String authCode = (String)request.getSession().getAttribute("authCode");
//        String vCode = (String)request.getSession().getAttribute("vCode");
//        System.out.println(vCode);
//        result = userService.register(user);
//        if(!authCode.equals((inputCode))){
//            reminder = "验证码有误，请重新输入！";
//            model.addAttribute("reminder", reminder);
//            return "/account/Register";
//        }
//        else if (result == true) {
//            HttpSession session = request.getSession();
//            session.setAttribute("user",user);
//            return "/catalog/Main";
//        } else {
//            reminder = "该用户名已注册，请重新输入！";
//            model.addAttribute("reminder", reminder);
//            return "/account/Register";
//        }
//    }
    @PostMapping("/register")
    public CommonResponse<Object> register(
                                           @RequestParam("id") String id,
                                           @RequestParam("password") String password,
                                            @RequestParam("firstname") String firstname,
                                            @RequestParam("lastname") String lastname,
                                           @RequestParam("email") String email,
                                           @RequestParam("phone") String phone,
                                           @RequestParam("address1") String address1,
                                           @RequestParam("address2") String address2,
                                           @RequestParam("city") String city,
                                           @RequestParam("state") String state,
                                           @RequestParam("zip") String zip,
                                           @RequestParam("country") String country,
                                           HttpSession session){
        String reminder= null;
        boolean result = false;
        User user=new User();
        user.setUsername(id);
        user.setPassword(password);
        user.setFirstname(firstname);
        user.setLastname(lastname);
        user.setEmail(email);
        user.setPhone(phone);
        user.setAddress1(address1);
        user.setAddress2(address2);
        user.setCity(city);
        user.setState(state);
        user.setZip(zip);
        user.setCountry(country);

        User u1 = userService.findUserByUsername(user.getUsername());

        if (u1 == null) {
            userService.register(user);
            session.setAttribute("userInfo",user);
            return CommonResponse.createForSuccessMessage("success");
        } else {
            reminder = "该用户名已注册，请重新输入！";
            return CommonResponse.createForError(reminder);
        }
    }
@PostMapping("/signout")
    public void signout(HttpSession session){
        session.invalidate();
    }
    @PostMapping("/saveAccount")
    public void saveAccount(@RequestParam("userId") String userId,
            @RequestParam("password") String password,
                              @RequestParam("firstname") String firstname,
                              @RequestParam("lastname") String lastname,
                              @RequestParam("email") String email,
                              @RequestParam("phone") String phone,
                              @RequestParam("address1") String address1,
                              @RequestParam("address2") String address2,
                              @RequestParam("city") String city,
                              @RequestParam("state") String state,
                              @RequestParam("zip") String zip,
                              @RequestParam("country") String country,
                              @RequestParam("languagepre") String languagepre,
                              HttpSession session){
        User user=new User();
        user.setUsername(userId);
        user.setPassword(password);
        user.setFirstname(firstname);
        user.setLastname(lastname);
        user.setEmail(email);
        user.setPhone(phone);
        user.setAddress1(address1);
        user.setAddress2(address2);
        user.setCity(city);
        user.setState(state);
        user.setZip(zip);
        user.setCountry(country);
        user.setLanguagepre(languagepre);
        String message = null;
        boolean result = userService.updateUserByUsername(user);
        if(result == true){
            session.setAttribute("user",user);
        }
        else{
            message = "申请失败，请重新输入！";
            session.setAttribute("message",message);

        }
    }


//    @GetMapping("/usernameIsExist")
//    public void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//        String username = request.getParameter("username");
//        User user = userService.findUserByUsername(username);
//
//        response.setContentType("text/plain");
//        PrintWriter out = response.getWriter();
//
//        if(username==""){
//            out.print("Empty");
////            System.out.println("empty");
//        }
//        else if(user != null){
//            out.print("Exist");
////            System.out.println('E');
//        }
//        else {
//            out.print("Not Exist");
////            System.out.println("NE");
//        }
//
//        out.flush();
//        out.close();
//
//
//    }




    @GetMapping("/allOrders")
    public CommonResponse<Object> ViewAllOrders(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<Order> orderList = orderService.getOrdersByUserId(user.getUsername());
        System.out.println(orderList);
        System.out.println(user.getUsername());
        return CommonResponse.createForSuccess(orderList);
    }
//   @GetMapping("/getLineItemId")
//    public void getLineItemId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//      String categoryId = request.getParameter("orderId");
//       System.out.println(categoryId+"aaa");
//      int lineItemId = Integer.parseInt(categoryId);
//        //System.out.println(categoryId+"             ddddddddd");
//        List<LineItem> lineItems = orderService.getLineItemsByOrderId(lineItemId);
//       for(LineItem lineItem:lineItems){
//            System.out.println(lineItem.getItemId());
//        }
//        response.setContentType("text/xml");
//        PrintWriter out = response.getWriter();
//        String mouseevent = " ";
//        mouseevent = categoryId+ "\n";
//        int i = 0;
//        while(i < lineItems.size()){
//           LineItem lineItem = lineItems.get(i);
//            mouseevent += lineItem.getItemId()+ "\n";
//            i++;
//        }
//
//
//        out.write(mouseevent);
//        out.flush();
//        out.close();
//   }
}
